﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace MediaController.Utils
{
    public class ConsoleRedirector : TextWriter
    {
        private readonly TextBox _output;

        public ConsoleRedirector(TextBox output)
        {
            _output = output;
            _output.TextChanged += OutputTextChanged;
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }

        public override void Write(char value)
        {
            base.Write(value);
            var builder = new StringBuilder(_output.Text);
            builder.Append(value.ToString());
            if (_output.InvokeRequired)
            {
                _output.Invoke(new Action<char>(Write), value);
            }
            else
            {
                _output.Text = builder.ToString();
            }
        }

        void OutputTextChanged(object sender, EventArgs e)
        {
            _output.Select(_output.Text.Length - 1, _output.Text.Length - 1);
            _output.ScrollToCaret();
        }
    }
}